﻿using HelperLibrary;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace AVCJobDispatcherWindows.TaskJobEngine
{
    public class TaskJobManager
    {
        public static List<JobInfo> JobList = new List<JobInfo>();
        private static readonly object _locker = new object();
        //线程
        private static Thread TimingThread;
        private static bool IsTrue = true;
        //版本号
        public static string version=string.Empty;
        //发送时间
        public static int sendTime = 0;

        public static int startCount = 0;

        public static void AddJobInfo(JobInfo jobInfo)
        {
            lock (_locker)
            {
                JobInfo existedJob = JobList.FirstOrDefault(j => j.Id == jobInfo.Id);
                if (existedJob != null)
                {
                    JobList.Remove(existedJob);
                }
                JobList.Add(jobInfo);
            }
        }

        //启动任务
        public static async void Start(IConfigurationRoot configuration)
        {
            List<SysJob> sysJobArr = new List<SysJob>();
            try
            {
                await Task.Run(() => {
                    MqttInfo mqttInfo = new MqttInfo();
                    configuration.GetSection("MqttOption").Bind(mqttInfo);
                    configuration.GetSection("SysJobArr").Bind(sysJobArr);
                    FmMqttClient.ConnectMqttServerAsync(mqttInfo);
                });
            }
            catch (Exception ex)
            {
                LogHelper.LogErr(ex);
            }
            version = configuration["Version"];
            sendTime = Convert.ToInt32(configuration["SendTime"]);
            foreach (SysJob sysJob in sysJobArr)
            {
                if (!sysJob.IsDispatch)
                {
                    continue;
                }
                foreach (JobInfo jobInfo in sysJob.TaskJobs)
                {
                    jobInfo.ExecuteUrl = $"{sysJob.ServerHost}{jobInfo.ExecuteUrl}";
                }
                startCount += sysJob.TaskJobs.Count();
                JobList.AddRange(sysJob.TaskJobs);
            }

            if (JobList.Any())
            {
                foreach (var configJob in JobList)
                {
                    await Worker.ExecuteFixedJobAsync<TaskJob>(configJob);
                }
            }
            TimingThread = new Thread(TimeingThread);
            TimingThread.IsBackground = true;
            TimingThread.Start();
        }

        public static void TimeingThread(object obj)
        {
            while (IsTrue)
            {
                try
                {
                    var ips = NetworkInterface.GetAllNetworkInterfaces()
                          .OrderByDescending(c => c.Speed)
                          .FirstOrDefault(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up);
                    if (ips != null)
                    {
                        string ip = ips.GetIPProperties().UnicastAddresses
                   .Where(p => p.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !System.Net.IPAddress.IsLoopback(p.Address))
                   .FirstOrDefault()?.Address.ToString();
                        SendDataInfo sendDataInfo = new SendDataInfo
                        {
                            ip_addr = ip,
                            source = "jds",
                            version = version,
                            startcount = startCount
                        };
                        FmMqttClient.Publish(JsonConvert.SerializeObject(sendDataInfo));
                    }
                    Thread.CurrentThread.Join(sendTime * 60 * 1000);
                }
                catch (Exception ex)
                {
                    LogHelper.LogErr(ex);
                }
            }
        }
    }
}
